<template>
  <div class="mainPage">
    <div class="searchRow">
      <div class="inputRow">
        <div class="inputBox">
          <div class="labelText">名称：</div>
          <a-input v-model:value="queryForm.pageModel.query.name0" placeholder="名称" @change="inputChange"
            @pressEnter="handleFind" :allowClear="true"></a-input>
        </div>
      </div>
      <div class="btnBox">
        <a-button type="primary" @click="handleFind" class="queryBtn">
          查询
        </a-button>
        <a-button class="resetBtn" @click="reset">重置</a-button>
      </div>
    </div>


    <div class="tableOperation">
      <div class="operationBtn">
        <a-button type="primary" @click="showAddModel" class="queryBtn">
          新增
        </a-button>
      </div>
      <a-table :columns="tableData.columns" :data-source="tableData.dataSource" :loading="tableLoading"
        class="custom-table" style="padding: 10px;" :pagination="pagination" :onChange="onTableChange">
        <template #headerCell="{ column }">
          <template v-if="column.key === 'index'">
            <span>
              序号
            </span>
          </template>
          <template v-if="column.key === 'name'">
            <span>
              {{ column.name }}
            </span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'img'">
            <a-image style="max-width: 200px;max-height: 200px" :src="record.img" />
          </template>
          <template v-else-if="column.key === 'action'">
            <div style="display: flex;justify-content: center;">
              <span class="actionBtn">
                <a class="deleteBtn" @click="showDeleteConfirm(record.id)">删除</a>
              </span>
              <span class="actionBtn">
                <a class="editBtn" @click="showEditModel(record)">编辑</a>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>


    <a-modal v-model:open="editModel" title="编辑食材" @ok="handleEdit">
      <template #footer>
        <a-button class="cancelBtn" key="back" @click="editModel = false">取消</a-button>
        <a-button class="confirmBtn" key="submit" type="primary" :loading="loading" @click="handleEdit">确定</a-button>
      </template>

      <a-form ref="formRef" :model="editRecord" :rules="rules">
        <a-form-item label="食材" name="name">
          <a-input v-model:value="editRecord.name" disabled />
        </a-form-item>
        <a-form-item label="类别" name="categoryShowId">
          <a-cascader expand-trigger="hover" v-model:value="editRecord.categoryShowId" :options="categoryOptions"
            placeholder="请选择" :allowClear="false" />
        </a-form-item>
        <!-- <a-form-item label="单位" name="unit">
          <a-select ref="select" v-model:value="editRecord.unit">
            <a-select-option v-for="item in unitOptions" :key="item.id" :value="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="图片" name="img">
          <a-upload v-model:file-list="fileList" list-type="picture-card" @preview="handlePreview"
            :customRequest="customRequest" :before-upload="beforeUpload" @remove="handleRemove">
            <div v-if="fileList.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
          <a-modal :open="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item :label="$t('common.remark')" name="remark">
          <a-textarea v-model:value="editRecord.remark" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="addModel" title="新增食材" @ok="handleAdd">
      <template #footer>
        <a-button class="cancelBtn" key="back" @click="editModel = false">{{ $t('common.cancel') }}</a-button>
        <a-button class="confirmBtn" key="submit" type="primary" :loading="loading"
          @click="handleAdd">{{ $t('common.confirm') }}</a-button>
      </template>

      <a-form ref="formRef" :model="editRecord" :rules="rules">
        <a-form-item label="食材" name="name">
          <a-input v-model:value="editRecord.name" />
        </a-form-item>
        <a-form-item label="类别" name="categoryShowId">
          <a-cascader expand-trigger="hover" v-model:value="editRecord.categoryShowId" :options="categoryOptions"
            placeholder="请选择" :allowClear="false" />
        </a-form-item>
        <a-form-item label="图片" name="img">
          <a-upload v-model:file-list="fileList" list-type="picture-card" @preview="handlePreview"
            :customRequest="customRequest" :before-upload="beforeUpload" @remove="handleRemove">
            <div v-if="fileList.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">{{ $t('common.upload') }}</div>
            </div>
          </a-upload>
          <a-modal :open="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item :label="$t('common.remark')" name="remark">
          <a-textarea v-model:value="editRecord.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { add, deleteIngredient, edit, findDetail, pageList } from '@/api/ingredient.js';
import { findList } from '@/api/ingredientCategory.js';
import { findUnitList } from '@/api/unit.js';
import { baseURL } from '@/utils/request.js';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import axios from 'axios';
import { computed, createVNode, onMounted, reactive, ref } from 'vue';
// 表格加载动画
const tableLoading = ref(false);
// 表格数据
const tableData = reactive({
  // 数据列
  columns: [
    {
      name: '序号',
      dataIndex: 'index',
      key: 'index',
      customRender: ({ index }) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      name: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '图片',
      dataIndex: 'img',
      key: 'img',
    },
    {
      title: '类别',
      dataIndex: 'categoryName',
      key: 'categoryName',
    },
    {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark',
    },
    // {
    //   title: '单位',
    //   key: 'unit',
    //   dataIndex: 'unit',
    // },
    {
      title: '操作',
      key: 'action',
    }
  ],
  // 数据列表
  dataSource: []
});
// 食材类别列表
const categoryOptions = ref([]);
// 单位列表
const unitOptions = ref([]);
// 是否回到第一页
const isReturnFirstPage = ref(false);
// 新增弹框
const addModel = ref(false);
// 规则校验
const rules = {
  name: [
    {
      required: true,
      message: '请输入食材名称',
      trigger: 'change',
    },
  ],
  unit: [
    {
      required: true,
      message: '请输入单位',
      trigger: 'change',
    },
  ],
  categoryShowId: [
    {
      required: true,
      message: '请选择食材类别',
      trigger: 'change',
    },
  ]
};

// 定义响应式的分页对象
const pagination = reactive({
  class: 'myPagination',
  total: 0, // 总条数
  current: 1, // 当前页数
  pageSize: 10, // 每页显示的条数
  // pageSizeOptions: ['10', '20', '30', '40', '50'],
  showSizeChanger: true, // 是否可以改变每页显示的条数
  showQuickJumper: true, // 是否可以快速跳转到指定页
  showTotal: (total) => `共 ${total} 条`, // 显示总条数和当前数据范围
  onShowSizeChange: (current, pageSize) => handleShowSizeChange(current, pageSize), // 改变每页数量时更新显示
  onChange: (page, pageSize) => handleShowPageChange(page, pageSize) // 页码改变时的回调函数
});

// 查询条件
const queryForm = computed(() => {
  return {
    pageModel: {
      pageNow: pagination.current,
      pageSize: pagination.pageSize,
      query: {
        name0: '',
      },
      sort: ['1create_time'],
    }
  }
});
// 编辑弹框展示
const editModel = ref(false);
const editRecord = reactive({
  id: '',
  name: '',
  img: '',
  categoryId: '',
  categoryShowId: '',
  remark: '',
  unit: '',
});

// 预览参数
const previewVisible = ref(false);
// 预览图片地址
const previewImage = ref('');

onMounted(() => {
  setTimeout(() => {
  }, 10000000)
  initData();
})

const initData = () => {
  // 获取食材数据
  getTableData();
  // 获取食材分类
  getCategoryData();
  // 获取单位列表
  getUnitData();
}

const getTableData = () => {
  tableLoading.value = true;
  pageList(queryForm.value).then(res => {
    console.log(res);
    if (res.code === 200) {
      let list = res.data.list;
      tableData.dataSource = list.dataList;
      pagination.total = list.total;
    }
  }).finally(() => {
    tableLoading.value = false;
  })
}

const getCategoryData = () => {
  findList().then(res => {
    if (res.code === 200) {
      categoryOptions.value = res.data;
    }
  })
}

const getUnitData = () => {
  findUnitList().then(res => {
    if (res.code === 200) {
      unitOptions.value = res.data;
    }
  })
}

// 定义展开行的键
const expandedRowKeys = ref([]);

// 处理每页显示条数改变的函数
const handleShowSizeChange = (current, pageSize) => {
  console.log(current, pageSize);
  pagination.pageSize = pageSize;
};

// 处理页码改变的函数
const handleShowPageChange = (page, pageSize) => {
  console.log('handleShowPageChange.', page, pageSize, isReturnFirstPage.value);
  expandedRowKeys.value = [];
  if (isReturnFirstPage.value) {
    pagination.current = 1;
    isReturnFirstPage.value = false;
  } else {
    pagination.current = page;
  }
};

const onTableChange = () => {
  console.log('ontablechange');

  getTableData();
}

const handleFind = () => {
  getTableData();
}
const inputChange = () => {
  console.log('inputChange');
  getTableData();
}
// 确认删除弹框
const showDeleteConfirm = (id) => {
  Modal.confirm({
    title: '系统消息',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定要删除吗?',
    okText: '是',
    okType: 'danger',
    cancelText: '否',
    onOk() {
      deleteOne(id);
    },
    onCancel() {
    },
  });
}
// 展示新增框
const showAddModel = () => {
  addModel.value = true;
  editRecord.name = '';
  editRecord.img = '';
  editRecord.id = '';
  editRecord.categoryId = '';
  editRecord.categoryShowId = '';
  editRecord.remark = '';
  editRecord.unit = '';
  fileList.value = [];
}
// 新增
const handleAdd = () => {
  editRecord.categoryId = editRecord.categoryShowId[editRecord.categoryShowId.length - 1]
  add(editRecord).then(res => {
    if (res.code === 200) {
      message.success('添加成功');
      addModel.value = false;
      getTableData();
    }
  })
}
// 删除
const deleteOne = (id) => {
  deleteIngredient(id).then(res => {
    console.log(res);
    if (res.code === 200) {
      message.success('删除成功');
    }
    getTableData();
  })
}
// 展示编辑弹框
const showEditModel = (record) => {
  editModel.value = true;
  findDetail(record.id).then(res => {
    if (res.code === 200) {
      let data = res.data;
      editRecord.id = data.id;
      editRecord.name = data.name;
      editRecord.img = data.img;
      editRecord.unit = data.unit;
      editRecord.remark = data.remark;
      editRecord.categoryShowId = data.categoryShowIdList;
      if (data.img) {
        fileList.value = [{
          uid: '-1',
          name: '',
          status: 'done',
          url: data.img,
        }];
      } else {
        fileList.value = [];
      }
      imageUrl.value = data.img
    }
  })
}
const handleEdit = () => {
  editRecord.categoryId = editRecord.categoryShowId[editRecord.categoryShowId.length - 1]
  edit(editRecord).then(res => {
    if (res.code === 200) {
      message.success('编辑成功');
      editModel.value = false;
      getTableData();
    }
  })
}

const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
// 上传图片
const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
  }
  ;
}

// 上传图片前校验
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传jpg、png、jpeg格式的文件');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片不能超过2MB');
  }
  return isJpgOrPng && isLt2M;
};

// 上传文件
const customRequest = ({ file }) => {
  const formData = new FormData();
  formData.append('file', file);
  // 发送 POST 请求
  axios.post(baseURL + 'api/file/upload', formData).then(res => {
    if (res.data.code === 200) {
      imageUrl.value = res.data.data;
      file.url = res.data.data;
      editRecord.img = res.data.data;
      message.success('上传成功')
    } else {
      message.error('上传失败')
    }
    let newFileList = [];
    for (let i = 0; i < fileList.value.length; i++) {
      let one = fileList.value[i];
      if (one.originFileObj) {
        newFileList.push(one.originFileObj)
      }
    }
    fileList.value = [];
    fileList.value = [...newFileList];
    loading.value = false;
  }).finally(() => {
    loading.value = false;
  })
};
// 预览文件
const handlePreview = async file => {
  previewImage.value = imageUrl.value
  previewVisible.value = true;
};
// 删除
const handleCancel = () => {
  previewVisible.value = false;
};
// 移除图片
const handleRemove = () => {
  editRecord.img = null;
  previewVisible.value = false;
};
const reset = () => {
  console.log(queryForm.value);
  queryForm.value.pageModel.query.name0 = '';
  getTableData();
}
</script>

<style scoped lang="scss">
.css-dev-only-do-not-override-1p3hq3p {
  background-color: #fff;
}

.tableOperation {
  .operationBtn {
    background-color: #fff;
    display: flex;
    justify-content: right;
    padding: 20px 20px 0 0;
  }
}

.searchRow {
  display: flex;
  background-color: #fff;
  padding: 20px;
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;

  .inputRow {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .inputBox {
      display: flex;
      align-items: center;
      margin-right: 70px;
      margin-top: 10px;
      margin-bottom: 10px;

      .labelText {
        white-space: nowrap;
        font-size: 14px;
      }

      .selectClass {
        width: 199px;
      }
    }
  }

  .btnBox {
    display: flex;
    flex-wrap: nowrap;

    button {
      margin: 10px 0 10px 9px;
    }

    .ant-btn:first-child {
      margin-right: 8px !important;
    }
  }
}

.ant-spin-container>.myPagination {
  position: absolute;
  right: 0;
  display: block;
  text-align: right;
  background-color: #fff;

  .ant-pagination-total-text {
    float: right;
    margin-left: 10px;
    line-height: 32px;
  }

  .ant-pagination-options {
    .ant-pagination-options-size-changer {
      position: absolute;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      left: 0;
      bottom: 0;

      &:before {
        content: '每页显示';
        color: rgba(0, 0, 0, 0.45);
        word-break: keep-all;
        overflow-wrap: nowrap;
        margin-right: 10px;
      }

      .ant-select-item {
        text-align: start !important;
      }
    }
  }
}



.myPagination {
  @media (max-width: 480px) {

    .ant-pagination-item,
    .ant-pagination-options {
      margin-top: 8px;
    }

    .ant-pagination-total-text {
      float: none;
      display: block;
      text-align: center;
    }
  }
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
